﻿#include "UdpMulticastReceiver.h"
#include <QHostAddress>
#include <QDebug>
#include<QDataStream>

UdpMulticastReceiver::UdpMulticastReceiver(QObject *parent)
    : QObject(parent), udpSocket1(new QUdpSocket(this)),
      filePls(nullptr), isRunning(false)
{
    checkAndCreateDataDir();
}

void UdpMulticastReceiver::start(const QString &multicastGroup,quint16 port)
{
    if (isRunning) return;
    initializeSocket(udpSocket1, port, multicastGroup);
    connect(udpSocket1, &QUdpSocket::readyRead, this, [this]() { readPendingDatagrams(udpSocket1); });
    isRunning = true;
}

void UdpMulticastReceiver::start_wt()
{
    createNewFile();
}

void UdpMulticastReceiver::stop()
{
    if (!isRunning) return;

    udpSocket1->abort();
    delete udpSocket1;
    udpSocket1 = nullptr;

    mutex.lock();
    if (filePls) {
        filePls->close();
        delete filePls;
        filePls = nullptr;
    }


    mutex.unlock();

    isRunning = false;
}
void UdpMulticastReceiver::stop_wt()
{
    mutex.lock();
    if (filePls) {
        filePls->close();
        delete filePls;
        filePls = nullptr;
    }
    mutex.unlock();
}

void UdpMulticastReceiver::readPendingDatagrams(QUdpSocket *socket)
{

    while (socket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(socket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;
        socket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
        if (filePls) {
            processReceivedData(datagram);
        }
    }
}

void UdpMulticastReceiver::initializeSocket(QUdpSocket *socket, quint16 port, const QString &multicastGroup)
{
    // 绑定到 AnyIPv4 地址
    socket->bind(QHostAddress::AnyIPv4, port, QUdpSocket::ShareAddress);
    socket->joinMulticastGroup(QHostAddress(multicastGroup));
}

void UdpMulticastReceiver::processReceivedData(const QByteArray &data) {
    // 检查包头是否为0xF020
    quint16 header = (data[0] << 8) + data[1];
    if (header == 0xF020) {
        // 锁定互斥体
        mutex.lock();

        // 写入.pls文件
        if (filePls) {
            if (filePls->size() > fileSizeLimit) {
                createNewFile();
            } else {
                filePls->write(data.data(),data.size());
            }
        }else {
            return;
        }
        mutex.unlock();
    } else {
        // 如果包头不是0xAA55，这里可以根据需要处理其他类型的数据包
        //qDebug()<<header;
    }
}

void UdpMulticastReceiver::createNewFile()
{

    QDateTime now = QDateTime::currentDateTime();
    QString baseName = now.toString("yyyyMMddhhmmss");

    QString filePathPls = dataPath + QDir::separator() + baseName + ".dat";

    if (filePls) {
        filePls->close();
        delete filePls;
    }

    QFile *newFilePls = new QFile(filePathPls);

    if (newFilePls->open(QIODevice::WriteOnly)) {
        filePls = newFilePls;
    } else {
        qDebug() << "Failed to open file:" << filePathPls;
        delete newFilePls;
    }
}

void UdpMulticastReceiver::checkAndCreateDataDir()
{
    dataPath = QDir::fromNativeSeparators("G:/radar_data");
    //dataPath = QDir::currentPath() + QDir::separator() + "data";
    QDir dir(dataPath);
    if (!dir.exists()) {
        dir.mkpath(dataPath);
    }
}

